package ch.usi.inf.pf2;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;

import ch.usi.inf.pf2.cell.Cell;
import ch.usi.inf.pf2.cell.Formula;
import ch.usi.inf.pf2.alu.*;

/**
 * The Listener class is a class that stores the changes occurred in the spreadsheet.
 * @author Lorenzo Baracchi, Ebrisa Savina Mastrodicasa
 *
 */
public class Listener {

	private LinkedList<Cell> changedCells;
	private LinkedList<PossibleChanges> changeDone;
	private HashMap<Cell, String> formulas;
	private ALU alu;

	/**
	 * Construct a Listener object
	 */
	public Listener (Sheet sheet) {
		changedCells = new LinkedList<Cell>();
		changeDone = new LinkedList<PossibleChanges>();
		formulas= new HashMap<Cell, String>();
		alu = new ALU(sheet);
	}

	/**
	 * Adds a cell to the ArrayList<Cell>
	 * @param cell The cell to be added
	 */
	public void addChangedCell(Cell cell, PossibleChanges change, String cellReference) {
		changedCells.addLast(cell);
		changeDone.addFirst(change);
		if (formulas.get(cell) == null) {
			if(cell.getContent() instanceof Formula)
				formulas.put(cell, cellReference);
			System.out.println(formulas.size());
		} else {
			if(cell.getContent() instanceof Formula) {
				formulas.put(cell, cellReference);
			} else {
				formulas.remove(cell);
			}
		}
	}

	/**
	 * Clear the ArrayList of Cells. 
	 */
	public void clearList() {
		changedCells.clear();
		changeDone.clear();
	}

	/**
	 * Change the last modified cell performing the correct
	 * computations.
	 */
	public void evaluateFirst ()
	{
		PossibleChanges change = changeDone.getFirst();
		if(change == PossibleChanges.DATA) 
		{
			alu.computeHashSetOfFormulas(formulas);
		}
	}
}
